package gateway.provider;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import framework.config.SecurityConfig;
import framework.vo.R;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关异常通用处理器
 */
@Order(-1)
@Component
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final SecurityConfig securityConfig;

    public GlobalExceptionConfiguration(SecurityConfig securityConfig) {
        this.securityConfig = securityConfig;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        // committed
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 输导异常页面
        if (StringUtils.hasText(securityConfig.getRedirectOnAuthError())) {
            response.setStatusCode(HttpStatus.FOUND);
            response.getHeaders().add("Location", securityConfig.getRedirectOnAuthError());
            return response.setComplete();
        }

        // set status
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }

        // output
        return response
                .writeWith(Mono.fromSupplier(() -> {
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    try {
                        return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage())));
                    } catch (JsonProcessingException e) {
                        return bufferFactory.wrap(e.getMessage().getBytes(StandardCharsets.UTF_8));
                    }
                }));
    }
}

